<template>
  <view class="page-main">
    <div>
      <view class="header-section">
        <image src="../../static/muban1.png" class="header-icon"></image>
        <view class="plan-name-section">
          <view class="input-wrapper">
            <text class="input-label">模板名称：</text>
            <input
              v-model="templateData.planName"
              placeholder="请输入模板名称"
              class="plan-name-input"
            />
          </view>
        </view>
      </view>

      <div style="padding: 30rpx">
        <div v-for="(node, nodeIndex) in templateData.nodes" :key="nodeIndex">
          <view class="f ac xb mt20r">
            <view
              class="title f ac rds20r"
              style="
                background-color: #fff;
                color: #000;
                padding: 0 10rpx;
                height: 70rpx;
              "
              @click="changePurpose(nodeIndex)"
            >
              <u-icon name="edit-pen"></u-icon>
              <div style="margin-left: 10rpx">{{ node.purpose }}</div>
            </view>
            <view
              class="add"
              style="
                height: 70rpx;
                display: flex;
                align-items: center;
                justify-content: center;
              "
              @click="
                () => {
                  currentNode = nodeIndex;
                  show2 = true;
                }
              "
            >
              添加动作
            </view>
            <view
              class="delete"
              style="
                height: 70rpx;
                display: flex;
                align-items: center;
                justify-content: center;
                margin-left: 10rpx;
              "
              @click="deleteNode(nodeIndex)"
            >
              <image src="../../static/del.png" class="delete-icon"></image>
            </view>
          </view>

          <div v-if="node.exercises && node.exercises.length > 0">
            <view
              v-for="(exercise, eIndex) in node.exercises"
              :key="eIndex"
              class="f ac xb mt30r plan chooseitem mt20r"
              @click="edit(exercise, eIndex, nodeIndex)"
            >
              <view class="f ac" style="flex: 1; justify-content: center">
                <text
                  v-if="!exercise.isEditing"
                  @click.stop="startEdit(nodeIndex, eIndex)"
                >
                  {{ exercise.name }}
                </text>
                <input
                  v-else
                  v-model="exercise.name"
                  class="name-input"
                  @blur="finishEdit(nodeIndex, eIndex)"
                  @click.stop
                  ref="nameInput"
                />
              </view>
              <view class="f ac" style="flex: 1; justify-content: center">
                <div>{{ exercise.sets }} 组 X</div>
                <div style="padding-right: 20rpx">
                  {{ exercise.reps.count
                  }}{{ getUnitLabel(exercise.reps.unit) }}
                </div>
              </view>
              <view class="f ac" style="flex: 1; justify-content: center">
                <div>{{ exercise.weighs }}</div>
              </view>
            </view>
          </div>
          <div v-else class="f ac xc mt30r plan chooseitem mt20r">暂无动作</div>
        </div>

        <div
          class="w100 f ac xc mt50r"
          style="padding: 0 10vw; box-sizing: border-box"
        >
          <view class="button-group">
            <view class="tc btn mr20r" style="width: 90%" @click="addmd">
              添加目的
            </view>
            <view class="tc btn" style="width: 90%" @click="saveTemplate">
              保存模板
            </view>
          </view>
        </div>
      </div>
    </div>
    <u-popup :show="show2" @close="resetForm" round>
      <view class="popup-content">
        <view class="form-item">
          <text class="label">动作名称：</text>
          <input
            v-model="form.name"
            placeholder="请输入动作名称"
            class="input-field"
          />
        </view>

        <view class="form-item">
          <text class="label">组数：</text>
          <input
            type="number"
            v-model="form.sets"
            placeholder="请输入组数"
            class="input-field-small"
          />
          <text class="unit-text">组</text>
        </view>

        <view class="form-item">
          <text class="label">次数：</text>
          <input
            type="number"
            v-model="form.reps.count"
            placeholder="请输入次数"
            class="input-field-small"
          />
          <picker
            mode="selector"
            :range="unitOptions"
            range-key="label"
            :value="unitIndex"
            @change="handleUnitChange"
            class="unit-picker"
          >
            <view class="picker-text">
              {{ unitOptions[unitIndex].label }}
              <u-icon name="arrow-down" size="24"></u-icon>
            </view>
          </picker>
        </view>

        <view class="form-item">
          <text class="label">重量：</text>
          <input
            v-model="form.weighs"
            placeholder="请输入重量"
            class="input-field"
          />
        </view>

        <view class="button-group f ac xb">
          <button class="reset-btn" @click="resetForm">重置</button>
          <button class="confirm-btn" @click="adddz">确定</button>
        </view>
      </view>
    </u-popup>
    <u-popup :show="show" @close="show = false">
      <view style="padding: 30rpx">
        <view
          v-for="(item, index) in mdList"
          :key="index"
          class="chooseitem mb20r f ac xb"
          @click="selId = item.id"
        >
          <view v-if="!item.slot" class="bodyr f ac">
            <!--                      <div class="mr20r" style="background: #00C853;width: 100rpx;height: 100rpx;"></div>-->
            {{ item.title }}
          </view>
          <view v-else>
            <div class="f ac">
              自定义：
              <input v-model="answer" type="text" />
            </div>
          </view>
          <image
            v-if="selId == item.id"
            class="sinchoose-on"
            mode=""
            src="/static/chooseon.png"
          ></image>
          <view v-else class="sinchoose"></view>
        </view>
        <view class="tc btn" style="width: 90%" @click="submit">确定</view>
      </view>
    </u-popup>
  </view>
</template>

<script>
import { addPlan, savePlanTemplate } from "../../api/fit";

export default {
  data() {
    return {
      templateData: {
        planName: "",
        nodes: [],
      },
      currentNode: 0, // 当前编辑的节点索引
      show: false,
      show2: false,
      form: {
        name: "", // 动作名称
        sets: "", // 组数
        reps: {
          count: "", // 次数
          unit: "c", // 单位：c=次数，s=秒数
        },
        weighs: "", // 重量
        interval: 30, // 默认间隔时间
      },
      mdList: [
        { id: 1, title: "热身" },
        { id: 2, title: "正式训练" },
        { id: 3, title: "放松拉伸" },
        { id: 4, title: "一般活动GPP" },
        { id: 5, title: "多次数RP" },
        { id: 6, title: "肌力ME" },
        { id: 7, title: "爆发DE" },
        { id: 8, title: "自定义", slot: true },
      ],
      answer: "",
      selId: 0,
      editIndex: "",
      unitIndex: 0,
      unitOptions: [
        { label: "次", value: "c" },
        { label: "秒", value: "s" },
        { label: "分", value: "m" },
      ],
    };
  },
  methods: {
    // 添加目的（节点）
    addmd() {
      this.templateData.nodes.push({
        purpose: "自定义",
        exercises: [],
      });
    },

    // 添加动作
    adddz() {
      if (!this.form.name) {
        uni.showToast({
          title: "请输入动作名称",
          icon: "none",
        });
        return;
      }

      // 检查必填字段
      if (!this.form.sets || !this.form.reps.count) {
        uni.showToast({
          title: "请填写组数和次数",
          icon: "none",
        });
        return;
      }

      const exercise = {
        name: this.form.name,
        sets: parseInt(this.form.sets),
        reps: {
          count: parseInt(this.form.reps.count),
          unit: this.form.reps.unit,
        },
        weighs: this.form.weighs || "", // 如果没有填写重量，使用空字符串
        interval: 30,
      };

      if (this.editIndex !== "") {
        // 修改现有动作
        this.templateData.nodes[this.currentNode].exercises[this.editIndex] =
          exercise;
      } else {
        // 添加新动作
        this.templateData.nodes[this.currentNode].exercises.push(exercise);
      }

      this.show2 = false;
      this.resetForm();
    },

    // 重置表单
    resetForm() {
      this.form = {
        name: "",
        sets: "",
        reps: {
          count: "",
          unit: "c",
        },
        weighs: "",
        interval: 30,
      };
      this.unitIndex = 0; // 重置单位选择器
      this.editIndex = "";
      this.show2 = false;
    },

    // 修改目的
    changePurpose(index) {
      this.currentNode = index;
      this.show = true;
    },

    // 确认修改目的
    submit() {
      const selectedPurpose = this.mdList.find(
        (item) => item.id === this.selId
      );
      if (selectedPurpose) {
        if (selectedPurpose.id === 8) {
          // 自定义目的
          this.templateData.nodes[this.currentNode].purpose = this.answer;
        } else {
          this.templateData.nodes[this.currentNode].purpose =
            selectedPurpose.title;
        }
      }
      this.show = false;
      // 重置选择状态
      this.selId = 0;
      this.answer = "";
    },

    // 开始编辑动作名称
    startEdit(nodeIndex, eIndex) {
      this.$set(
        this.templateData.nodes[nodeIndex].exercises[eIndex],
        "isEditing",
        true
      );
      // 等待 DOM 更新后聚焦输入框
      this.$nextTick(() => {
        const input = this.$refs.nameInput;
        if (input && input.length > 0) {
          input[input.length - 1].focus();
        }
      });
    },

    // 完成编辑动作名称
    finishEdit(nodeIndex, eIndex) {
      const exercise = this.templateData.nodes[nodeIndex].exercises[eIndex];
      if (!exercise.name.trim()) {
        uni.showToast({
          title: "动作名称不能为空",
          icon: "none",
        });
        exercise.name = exercise._originalName || "未命名动作";
      }
      this.$set(exercise, "isEditing", false);
    },

    // 修改编辑方法，保存原始名称
    edit(exercise, eIndex, nodeIndex) {
      this.currentNode = nodeIndex;
      this.editIndex = eIndex;
      // 保存原始名称
      exercise._originalName = exercise.name;
      // 深拷贝避免直接修改原对象
      this.form = JSON.parse(
        JSON.stringify({
          name: exercise.name,
          sets: exercise.sets,
          reps: exercise.reps,
          weighs: exercise.weighs || "",
          interval: exercise.interval || 30,
        })
      );
      this.unitIndex = this.unitOptions.findIndex(
        (opt) => opt.value === exercise.reps.unit
      );
      this.show2 = true;
    },
    getUnitLabel(unit) {
      const option = this.unitOptions.find((opt) => opt.value === unit);
      return option ? option.label : "";
    },

    handleUnitChange(e) {
      this.unitIndex = e.detail.value;
      this.form.reps.unit = this.unitOptions[this.unitIndex].value;
    },

    // 保存模板
    async saveTemplate() {
      // 验证模板名称
      if (!this.templateData.planName) {
        uni.showToast({
          title: "请输入模板名称",
          icon: "none",
        });
        return;
      }

      // 验证数据
      if (
        this.templateData.nodes.some(
          (node) => !node.exercises || node.exercises.length === 0
        )
      ) {
        uni.showToast({
          title: "请为每个目的添加至少一个动作",
          icon: "none",
        });
        return;
      }

      try {
        uni.showLoading({
          title: "保存中...",
        });
        const res = await savePlanTemplate(this.templateData);
        if (res.code === 200) {
          uni.showToast({
            title: "保存成功",
            icon: "success",
          });
          // 保存成功后返回上一页
          setTimeout(() => {
            uni.navigateBack();
          }, 1500);
        } else {
          throw new Error(res.msg || "保存失败");
        }
      } catch (error) {
        console.error("保存失败:", error);
        uni.showToast({
          title: error.message || "保存失败",
          icon: "none",
        });
      } finally {
        uni.hideLoading();
      }
    },

    // 删除节点
    deleteNode(index) {
      this.templateData.nodes.splice(index, 1);
    },
  },
};
</script>
<style lang="scss">
.page-main {
  padding: 15rpx;
  background: #efefef;
}

.header-section {
  display: flex;
  align-items: center;
  background-color: #000;
  padding: 30rpx;
  border-radius: 20rpx;
}

.header-icon {
  width: 100rpx;
  height: 100rpx;
  margin-right: 20rpx;
}

.plan-name-section {
  flex: 1;
}

.input-wrapper {
  display: flex;
  align-items: center;
  padding: 20rpx;
  background: #000;
  border-radius: 16rpx;
}

.input-label {
  font-size: 40rpx;
  color: #fff;
  white-space: nowrap;
}

.plan-name-input {
  flex: 1;
  height: 70rpx;
  font-size: 28rpx;
  padding: 0 20rpx;
  background: #fff;
  border-radius: 8rpx;
}

.popup-content {
  padding: 30rpx;
  width: 600rpx;
}

.form-item {
  display: flex;
  align-items: center;
  margin-bottom: 30rpx;
}

.label {
  width: 160rpx;
  font-size: 28rpx;
  color: #333;
  flex-shrink: 0;
}

.input-field {
  flex: 1;
  height: 70rpx;
  padding: 0 20rpx;
  border: 1rpx solid #ddd;
  border-radius: 8rpx;
  font-size: 28rpx;
}

.input-field-small {
  flex: 1;
  height: 70rpx;
  padding: 0 20rpx;
  border: 1rpx solid #ddd;
  border-radius: 8rpx;
  font-size: 28rpx;
  text-align: left;
}

.unit-text {
  margin-left: 20rpx;
  font-size: 28rpx;
  color: #666;
}

.unit-picker {
  margin-left: 20rpx;
  width: 140rpx;
}

.picker-text {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 70rpx;
  padding: 0 20rpx;
  border: 1rpx solid #ddd;
  border-radius: 8rpx;
  font-size: 28rpx;
}

.button-group {
  width: 100%;
  display: flex;
  justify-content: space-between;
  gap: 20rpx;
}

.btn {
  padding: 30rpx;
  background: #000;
  color: #fff;
  border-radius: 30rpx;
  transition: all 0.3s ease;

  &:active {
    opacity: 0.9;
    transform: translateY(2rpx);
  }
}

.reset-btn,
.confirm-btn {
  width: 200rpx;
  height: 80rpx;
  line-height: 80rpx;
  text-align: center;
  border-radius: 40rpx;
  font-size: 28rpx;
}

.reset-btn {
  background: #f5f5f5;
  color: #666;
}

.confirm-btn {
  background: #000;
  color: #fff;
}

// 列表项样式
.chooseitem {
  display: flex;
  align-items: center;
  padding: 20rpx;
  border: 1px solid #ebebeb;
  border-radius: 20rpx;
  margin-bottom: 20rpx;
}

.sinchoose {
  width: 28rpx;
  height: 28rpx;
  margin-right: 16rpx;
  border-radius: 50%;
  background: #ffffff;
  border: 2rpx solid #bfbdbd;
}

.sinchoose-on {
  width: 32rpx;
  height: 32rpx;
  margin-right: 16rpx;
}

// 通用样式
.btn {
  padding: 30rpx;
  background: #000;
  color: #fff;
  border-radius: 30rpx;
}

.mt20r {
  margin-top: 20rpx;
}

.mt30r {
  margin-top: 30rpx;
}

.ml20r {
  margin-left: 20rpx;
}

.mb20r {
  margin-bottom: 20rpx;
}

.f {
  display: flex;
}

.ac {
  align-items: center;
}

.xb {
  justify-content: space-between;
}

.xc {
  justify-content: center;
}

.title {
  flex: 1;
  margin-right: 20rpx;
  display: flex;
  align-items: center;
  padding: 16rpx 24rpx;
  background-color: #f4f1f4;
  color: #a385a1;
  border-radius: 20rpx;
  height: 70rpx; /* 设置与添加动作相同的高度 */

  .rds50 {
    margin-right: 12rpx;
  }

  .u-icon {
    margin-left: 12rpx;
  }
}

.add {
  padding: 0 24rpx;
  line-height: 70rpx;
  background: #000;
  color: #fff;
  border-radius: 30rpx;
  font-size: 26rpx;
  display: inline-block;
  line-height: 1.5;
  transition: all 0.3s ease;
  height: 70rpx; /* 设置与修改目的相同的高度 */

  &:active {
    opacity: 0.9;
    transform: scale(0.98);
  }
}

.delete {
  padding: 0 24rpx;
  line-height: 70rpx;
  background: #fff;
  color: #fff;
  border-radius: 30rpx;
  font-size: 26rpx;
  display: inline-block;
  line-height: 1.5;
  transition: all 0.3s ease;
  height: 70rpx; /* 设置与修改目的相同的高度 */

  &:active {
    opacity: 0.9;
    transform: scale(0.98);
  }
}

.delete-icon {
  width: 40rpx;
  height: 40rpx;
}

.rds20r {
  border-radius: 20rpx;
}

.rds50 {
  border-radius: 50%;
}

.w100 {
  width: 100%;
}

.tc {
  text-align: center;
}

.plan {
  background: #fff;
  border-radius: 16rpx;
  // padding: 30rpx;
}

.exercise-name {
  position: relative;
  min-width: 200rpx;

  .name-input {
    width: 100%;
    height: 60rpx;
    padding: 0 20rpx;
    border: 1px solid #ddd;
    border-radius: 8rpx;
    font-size: 28rpx;
    background: #fff;
  }
}

.chooseitem {
  // ... 其他样式保持不变 ...

  &:active {
    background: #f8f8f8;
  }
}
</style>
